package com.patent.service.impl;

import com.patent.common.DateUtil;
import com.patent.common.JsonUtil;
import com.patent.common.PatentConstant;
import com.patent.common.ResultCode;
import com.patent.common.ResultData;
import com.patent.dao.UserMapper;
import com.patent.domain.po.AuthCodeInfo;
import com.patent.domain.po.User;
import com.patent.service.AuthCodeService;
import com.patent.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

	@Resource(name="userMapper")
	private UserMapper userMapper;

	@Resource(name="authCodeService")
	private AuthCodeService authCodeService;

	@Override
	public User selectByUserMobile(String userMobile) {
		return userMapper.selectByUserMobile(userMobile);
	}

	@Override
	public int insertSelective(User record) throws Exception {
		return userMapper.insertSelective(record);
	}

	@Override
	public ResultData saveUserInfo(String source, String userMobile, String authCode) {
		ResultData resultData = new ResultData();

		AuthCodeInfo queryAuthCodeInfo = authCodeService.queryAuthCodeInfo(userMobile);
		System.out.println(JsonUtil.write2JsonStr(queryAuthCodeInfo));
		if(queryAuthCodeInfo != null){
			String queryAuthCode = queryAuthCodeInfo.getAuthCode();
			if(! authCode.equals(queryAuthCode)){
				//比较验证码
				resultData.setCode(ResultCode.varifyFailCode.getCode());
				resultData.setMsg("验证码输入错误");
				return resultData;
			}else{
				//比较是否过期
				Date createDate = queryAuthCodeInfo.getCreateDate();
				System.out.println("createDate:"+createDate);
				System.out.println("new Date():"+new Date());
				int second = DateUtil.getTimeDelta(createDate, new Date());
				System.out.println("second"+second);
				if(second > PatentConstant.validTime){
					resultData.setCode(ResultCode.invalidCode.getCode());
					resultData.setMsg(ResultCode.invalidCode.getMessage());
					return resultData;
				}
			}
			try {
				//验证手机号是否注册过
				User user = this.selectByUserMobile(userMobile);
				if(user == null){
					//保存用户信息到数据库
					User addUser = new User();
					addUser.setSource(source);
					addUser.setUserMobile(userMobile);
					userMapper.insertSelective(addUser);

				}
				resultData.setCode(ResultCode.success.getCode());
				resultData.setMsg(ResultCode.success.getMessage());
			} catch (Exception e) {
				resultData.setCode(ResultCode.paramError.getCode());
				resultData.setMsg("保存用户注册信息失败");
				return resultData;
			}
		}else{
			resultData.setCode(ResultCode.varifyFailCode.getCode());
			resultData.setMsg("验证码输入错误");
			return resultData;
		}
		return resultData;
	}

}
